import os
from flask import Blueprint, request, render_template, jsonify, current_app
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import fail_api, success_api, table_api
from applications.common.utils.rights import authorize
from sqlalchemy import text  # 导入 text 函数
from sqlalchemy import desc  # 导入 desc 函数
from flask_login import current_user
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import User, AdminLog
from applications.models import AccessLog
from applications.schemas import AccessLogOutSchema
from applications.view.system.api import get_ip_location as getip
from datetime import datetime

bp = Blueprint('access', __name__, url_prefix='/access')




#  网站基本设置-软件发布
@bp.get('/')
@authorize("system:access:main")
def main():
    db.create_all()
    return render_template('system/access/main.html')

#  查询数据
@bp.get('/table')
@authorize("system:access:main")
def data():
    # site = AccessLog.query.filter().all()
    # 查询参数构造
    mf = ModelFilter()
    # kami =  AccessLog.query.filter(mf.get_filter(AccessLog)).layui_paginate()
    kami = AccessLog.query.filter(mf.get_filter(AccessLog)).order_by(desc(AccessLog.access_time)).layui_paginate()
    count = kami.total
    # 返回api
    return table_api(data=model_to_dicts(schema= AccessLogOutSchema, data=kami.items), count=count)


#  添加数据
@bp.route('/save', methods=['POST','GET'])
def save():
    data = request.get_json()
    ip = request.headers.get('X-Forwarded-For') or request.remote_addr
    ip_data = getip()
    ip = ip_data.get('data').get('ip')
    country = ip_data.get('data').get('country')
    region = ip_data.get('data').get('region')
    city = ip_data.get('data').get('city')
    isp = ip_data.get('data').get('isp')
    position = ip_data.get('data').get('position')
    access_data = AccessLog(
        user_id=str_escape(data.get('user_id')),
        ip=ip,
        flowtotal =str_escape(data.get('flowtotal')),
        city=city,
        access_time=datetime.now(),
        url=str_escape(data.get('url')),
        referer=str_escape(data.get('referer')),
        userAgent=str_escape(data.get('userAgent')),
        isp =isp,
        position = position 
    )
    # print(access_data)
    try:
        db.session.add(access_data)
        db.session.commit()
        return success_api(msg="增加成功")
    except Exception as e:
        db.session.rollback()
        print(e)
        return fail_api(msg="增加失败")

    #    参数删除
# @bp.route('/remove/<int:id>', methods=['DELETE'])
@bp.route('/remove', methods=['post'])
@authorize("system:access:remove", log=True)
def delete():
    id = request.form.get('id')
    res = AccessLog.query.filter_by(id=id).delete()
    if not res:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")

# 批量删除
@bp.route('/batchRemove', methods=['post'])
@authorize("system:access:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = AccessLog.query.filter_by(id=id).delete()
        if not res:
            return fail_api(msg="批量删除失败")
    db.session.commit()
    return success_api(msg="批量删除成功")